<?php
/**
 * Created by PhpStorm.
 * User: yangliqiang
 * Date: 2018/8/31
 * Time: 22:03
 */

namespace app\api\models;

use Cm;
use Yii;
use yii\base\Model;

class WxModel extends Model
{
    public function actionGetAppId()
    {
        $cid = Cm::$req->post('company_id', ['title'=>'公司id']);

        $sql = "SELECT w.id,w.accountappid as appid,c.company_id 
        FROM `scrm_weixin_company_account` AS c 
        INNER JOIN `scrm_weixin_account` AS w ON  w.id=c.wx_account_id
        WHERE c.company_id='{$cid}'";

        $result = Cm::$db->one($sql);

        if (!$result) {
            $result = [];
        }

        Cm::$res->susess('success', $result);
    }

    public function actionSetAccountInfo()
    {
        $appid =  Cm::$req->post('appid', ['reg'=>'/^\w+/', 'title'=>'授权公众号id']);
        $appsecret =  Cm::$req->post('appsecret', ['reg'=>'/^\w+/', 'title'=>'授权公众号密钥']);
        $mch_id =  Cm::$req->post('mch_id', ['reg'=>'/^\d+/', 'title'=>'微信商户平台ID', 'null', 'empty']);
        $mch_key =  Cm::$req->post('mch_key', ['reg'=>'/[0-9A-Za-z]+/', 'title'=>'微信商户平台设置的支付密钥', 'null', 'empty']);

        $data = array_filter([
            'accountappsecret'=>$appsecret,
            'mch_id'=>$mch_id,
            'mch_key'=>$mch_key,
        ]);

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_account` WHERE accountappid='{$appid}'");

        if (!$result) {
            Cm::$res->error('未找到此公众号信息，不能编辑');
        }

        Cm::$db->update('scrm_weixin_account', $data, "accountappid='{$appid}'");

        Cm::$res->susess('保存成功！');
    }

    public function actionAuthorizerInfo()
    {
        $wxAppId = Cm::$req->post('appid');
        $appId = Yii::$app->params['wechat']['appid'];

//        $ticket = Cm::$db->one("SELECT component_verify_ticket,appsecret FROM `scrm_weixin_three_account` WHERE appid='{$appId}'");
//        if (!$ticket) {
//            Cm::$res->error('未配置微信第三方平台');
//        }
//        $wxinfo = (new \Auth([
//            'component_appid' => $appId,
//            'component_appsecret' => $ticket['appsecret'],
//            'component_verify_ticket' => $ticket['component_verify_ticket'],
//        ]))->get_authorizer_info($wxAppId, true);

        $info = Cm::$db->one("
          SELECT id,accountname,accountnumber,user_name,mch_id,mch_key,accountappsecret,
           accounttype,accountverifytype,func_info,status,qrcode_url,open_store,open_scan,open_pay,open_card,open_shake
          FROM `scrm_weixin_account`
          WHERE accountappid='{$wxAppId}'"
        );
//        if (!$info) {
//            $info = $wxinfo ? $wxinfo : [];
//        }
        if ($info['accountverifytype']) {

            $info['accountverifytype'] = in_array((int) $info['accountverifytype'], [-1, 1, 2]) ? 0 : 1;
        }

        Cm::$res->susess('success', $info);
    }
}